import { AppDataSource } from "@/config/database";
import { Customer } from "@/entities/basis/customer.entity";
import { Context } from "koa";

export interface IQuery {
    /** 页码 */
    page?: number,
    /** 每页数量 */
    pageSize?: number,
    /** 搜索关键词 */
    keyword?: string,
}

/** 获取客户列表 */
export async function getCustomerList(ctx: Context) {
    const { page = 1, pageSize = 10, keyword } = ctx.request.body as IQuery;

    const customerRepository = AppDataSource.getRepository(Customer);
    
    // 构建查询条件
    const queryBuilder = customerRepository.createQueryBuilder('customer');
    
    if (keyword) {
        queryBuilder.where(
            'customer.name LIKE :keyword OR customer.phone LIKE :keyword OR customer.email LIKE :keyword',
            { keyword: `%${keyword}%` }
        );
    }
    
    // 分页查询
    const [customers, total] = await queryBuilder
        .orderBy('customer.updatedAt', 'DESC')
        .skip((page - 1) * pageSize)
        .take(pageSize)
        .getManyAndCount();

    ctx.body = {
        items: customers,
        pagination: {
            total,
        }
    };
} 